package com.brotherly.mpgp;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.brotherly.framework.BaseActivity;
import com.brotherly.framework.service.ServiceManager;
import com.brotherly.mpgp.remoteinterface.RemoteServerService;
import com.brotherly.mpgp.remoteinterface.RemoteServerWatcher;
import com.brotherly.mpgp.util.GameManagerUtil;
import com.brotherly.mpgp.view.UpdateFreshListView;
import com.brotherly.mpgp.view.UpdateFreshListView.OnRefreshListener;

public class ArticleListActiviy extends BaseActivity
{

    private static final int COUNT_PER_PAGE = 10;

    private class ListAdapter extends BaseAdapter implements OnItemClickListener
    {
        private LayoutInflater mInflater;

        private JSONObject mArticles;

        public ListAdapter(Context context)
        {
            this.mInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount()
        {
            try
            {
                return mArticles == null ? 0 : mArticles.getJSONArray("articles").length();
            }
            catch (JSONException e)
            {
                e.printStackTrace();
                return 0;
            }
        }

        @Override
        public Object getItem(int position)
        {
            try
            {
                return mArticles == null ? null : mArticles.getJSONArray("articles").get(position);
            }
            catch (JSONException e)
            {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        public long getItemId(int position)
        {

            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            if (convertView == null)
            {
                convertView = (ViewGroup) mInflater.inflate(R.layout.article_list_item, null);
            }
            if (position % 2 == 0)
            {
                convertView.setBackgroundResource(R.drawable.list_item_background_1);
            } else
            {
                convertView.setBackgroundResource(R.drawable.list_item_background_2);
            }
            try
            {
                JSONObject item = (JSONObject) getItem(position);
                String type = item.getString("type");

                TextView title = (TextView) convertView.findViewById(R.id.tv_article_list_item_title);
                title.setText(item.getString("title"));
                View typeView = convertView.findViewById(R.id.v_type);
                Button getAccount = (Button) convertView.findViewById(R.id.btn_get_account);
                JSONObject info = null;
                JSONObject action = null;
                if (item.has("info"))
                {
                    info = item.getJSONObject("info");
                    if (info.has("action"))
                    {
                        JSONArray actions = info.getJSONArray("action");
                        if (actions.length() > 0)
                        {
                            action = actions.getJSONObject(0);
                        }
                    }
                }
                ImageView imageview = (ImageView) convertView.findViewById(R.id.iv_article_list_item_image);
                if (mIsShowPic)
                {
                    imageview.setVisibility(View.VISIBLE);
                    imageview.setImageResource(R.drawable.nopicture);
                    // imageview.setScaleType(ScaleType.CENTER_INSIDE);
                    loadArticleFirstImage(item, imageview);
                    title.setLines(2);
                } else
                {
                    imageview.setVisibility(View.GONE);
                    title.setLines(1);
                }
                if (action != null)
                {
                    getAccount.setVisibility(View.VISIBLE);
                } else
                {
                    getAccount.setVisibility(View.GONE);
                }
                if ("course".equals(type))
                {
                    typeView.setBackgroundColor(0xff7ac3c9);
                } else
                {
                    typeView.setBackgroundColor(0xfffc7a7e);
                }

                TextView content = (TextView) convertView.findViewById(R.id.tv_article_content);
                if (mIsShowPic)
                {
                    content.setVisibility(View.GONE);
                } else
                {
                    content.setVisibility(View.VISIBLE);
                    String contentStr = item.getString("content");
                    JSONArray contents = new JSONArray(contentStr);
                    for (int i = 0; i < contents.length(); i++)
                    {
                        if ("para".equals(contents.getJSONObject(i).getString("type")))
                        {
                            content.setText(contents.getJSONObject(i).getString("content"));
                        }
                    }
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            return convertView;
        }

        @Override
        public void notifyDataSetChanged()
        {
            JSONObject articles = GameManagerUtil.GameArticles.get(mPackageName);
            if (articles != null)
            {
                JSONTokener jsonParser = new JSONTokener(articles.toString());
                try
                {
                    mArticles = (JSONObject) jsonParser.nextValue();
                }
                catch (JSONException e)
                {
                    mArticles = null;
                }
            } else
            {
                mArticles = null;
            }
            mIsShowPic = getSharedPreferences("Setting", MODE_PRIVATE).getBoolean("isShowPic", false);
            super.notifyDataSetChanged();
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        {
            try
            {
                Intent intent = new Intent(ArticleListActiviy.this, ArticleActivity.class);
                intent.putExtra("PackageName", mPackageName);
                JSONArray articles = mArticles.getJSONArray("articles");
                intent.putExtra("Articles", articles.toString());
                intent.putExtra("Index", position - 1);
                startActivity(intent);
            }
            catch (Exception e)
            {

            }

        }
    }

    private UpdateFreshListView mListView;

    private String mPackageName;

    private ListAdapter mListAdapter;

    private TextView mTitle;

    private boolean mIsShowPic = true;

    private OnRefreshListener refreshListener = new OnRefreshListener()
    {
        @Override
        public void onRefresh(UpdateFreshListView listview)
        {
            gameArticles(0, COUNT_PER_PAGE);
        }

        @Override
        public void onLoadMore(UpdateFreshListView listview)
        {
            gameArticles(mNextIndex, COUNT_PER_PAGE);
        }
    };

    private void gameArticles(int index, int count)
    {
        List<String> gamesid = new ArrayList<String>();
        if (mPackageName != null)
        {
            gamesid.add(mPackageName);
        }
        RemoteServerService rss = (RemoteServerService) ServiceManager.getInstance().getService(
                ServiceManager.REMOTESEVER_SERVICE);
        rss.gameArticles(gamesid, index, count);
    }

    private void init()
    {
        mTitle = (TextView) findViewById(R.id.tv_title);
        mListView = (UpdateFreshListView) this.findViewById(R.id.listView);
        mListAdapter = new ListAdapter(this);
        mListView.setAdapter(mListAdapter);
        mListView.setOnRefreshListener(refreshListener);
        mListView.setDividerHeight(0);
        mListView.setOnItemClickListener(mListAdapter);
        ColorDrawable bg = new ColorDrawable();
        bg.setAlpha(1);
        mListView.setSelector(bg);
    }

    @Override
    public void onAllReady()
    {
        String pn = getIntent().getStringExtra("packageName");
        String name = getIntent().getStringExtra("GameName");
        if (mPackageName == null || !mPackageName.equals(pn))
        {
            mTitle.setText(name + "-秘籍");
            mPackageName = pn;
            mListView.setIsShowLoadMoreFooter(false);
            // showProgressDialog("读取数据中，请稍候！");
            mListView.requestFresh();
            // gameArticles(0, COUNT_DOWN_APP);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_article_list);
        init();
    }

    private int mNextIndex = 0;

    @Override
    protected void onServiceEvent(String id, Object param1, Object param2)
    {
        if (RemoteServerService.RemoteServer_Event_RemoteServer_Success.equals(id))
        {
            if (RemoteServerService.ACTION_GAME_ARTICLES.equals(param1))
            {
                final JSONObject articles = (JSONObject) param2;
                GameManagerUtil.updateGameArticles(this, mPackageName, articles);
                int count = 0;
                try
                {
                    count = GameManagerUtil.GameArticles.get(mPackageName).getJSONArray("articles").length();
                    mNextIndex = count
                            / COUNT_PER_PAGE;
                }
                catch (Exception e)
                {}
                final int c = count;
                runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        try
                        {
                            mListAdapter.notifyDataSetChanged();
                            mListView.onRefreshComplete();
                            mListView.notifyLoadMoreComplet();
                            boolean hasMore = c < articles.getInt("count");
                            mListView.setIsShowLoadMoreFooter(hasMore);
                        }
                        catch (Exception e)
                        {}

                    }
                });
            }
        } else if (Activity_Event_Internet_Resource_Download_Success.equals(id))
        {
            runOnUiThread(new Runnable()
            {

                @Override
                public void run()
                {
                    mListAdapter.notifyDataSetChanged();
                }
            });
        } else if (RemoteServerService.RemoteServer_Event_RemoteServer_Error.equals(id))
        {
            runOnUiThread(new Runnable()
            {
                @Override
                public void run()
                {
                    Toast.makeText(ArticleListActiviy.this, "您的网络不给力，请重试一下。", Toast.LENGTH_SHORT).show();
                    mListView.onRefreshComplete();
                    mListView.notifyLoadMoreComplet();
                }
            });
        }
    }

    public void loadArticleFirstImage(JSONObject article, ImageView imageview)
    {
        try
        {
            JSONArray contents = new JSONArray(article.getString("content"));
            for (int i = 0; i < contents.length(); i++)
            {
                JSONObject content = contents.getJSONObject(i);
                String type = content.getString("type");
                if ("image".equals(type))
                {
                    String key = content.getString("content");
                    int id = article.getJSONObject("info").getJSONArray(key).getJSONObject(0).getInt("id");
                    String imageurl = new StringBuffer(RemoteServerWatcher.RemoteServerRoot)
                            .append("articles/blob?ref=")
                            .append(id).toString();
                    // String cachePath = internetResourceDownload(imageurl);
                    // if (cachePath != null)
                    // {
                    // Bitmap bitmap = BitmapUtil.loadBitmap(cachePath);
                    // if (bitmap == null)
                    // {
                    // // removeCachedData(imageurl);
                    // // internetResourceDownload(imageurl);
                    // imageview.setImageResource(R.drawable.nopicture);
                    // // imageview.setScaleType(ScaleType.CENTER_INSIDE);
                    // } else
                    // {
                    // // imageview.setScaleType(ScaleType.CENTER_CROP);
                    // imageview.setImageBitmap(bitmap);
                    // }
                    // }
                    imageViewLoadInternetResource(imageview, imageurl, 0);

                    imageview.setTag(imageurl);
                    // imageview.setVisibility(View.VISIBLE);
                    break;
                }
            }
        }
        catch (Exception e)
        {}
    }
}
